package lzy.impl.smallspring.beans.factory.support.instantiate;

import lzy.impl.smallspring.beans.BeansException;
import lzy.impl.smallspring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class NativeInstantiationStrategy implements InstantiationStrategy {
    /**
     * @param beanDefinition
     * @param beanName
     * @param ctor
     * @param args
     * @return
     * @throws BeansException
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor<?> ctor, Object[] args) throws BeansException {
        Class<?> cls = beanDefinition.getBeanClass();
        try{
            if(ctor != null){
                // 为什么不直接调用ctor？
                return  cls.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }else {
                return cls.getDeclaredConstructor().newInstance();
            }
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}
